package life.majiang.community.provider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import life.majiang.community.dto.AccessTokenDTO;
import life.majiang.community.dto.GithubUser;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class GithubProvider {

    public String getAccessToken(AccessTokenDTO accessTokenDTO) {
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();

        // 这里需要把参数放入url中
        // RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenDTO));
        String modelUrl = "https://gitee.com/oauth/token?grant_type=authorization_code&code=%s&client_id=%s&redirect_uri=%s&client_secret=%s";
        String url = String.format(modelUrl, accessTokenDTO.getCode(), accessTokenDTO.getClient_id(),
                accessTokenDTO.getRedirect_uri(), accessTokenDTO.getClient_secret());
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(null, "")) /*发送空body*/
                .build();
        try (Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            // System.out.println(string);
            // String[] split = string.split(",");
            // String tokenstr = split[0];
            // String token = tokenstr.split(":")[1].split("\"")[1];

            JSONObject jsonObject = JSONObject.parseObject(string);
            String token = jsonObject.getString("access_token");

            return token;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public GithubUser getUser(String accessToken) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://gitee.com/api/v5/user?access_token=" + accessToken)
                .get()
                .build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            GithubUser githubUser = JSON.parseObject(string, GithubUser.class);
            return githubUser;
        } catch (IOException e) {
           e.printStackTrace();
        }
        return null;
    }
}
